<?php

namespace app\common\model\wechat;

use app\common\model\Base;
use think\db;

class WechatUser extends Base
{
    protected $name = 'wechat_user';

    public function getUserInfo($openid)
    {
        $field = 'wu.openid, wu.id, wu.nickname, wu.headimgurl, wu.sex, wu.member_id, m.username, m.nickname as m_nickname, m.avatar, m.status, m.invite_code, m.sex member_sex';
        $res = $this->alias('wu')->where(['wu.openid' => $openid]);
        $res = $res->join('member m', 'wu.member_id=m.id', 'LEFT')->field($field)->find();
        if (!empty($res)) {
            $res = $res->toArray();
            $res['nickname'] = $this->emojiDecode($res['nickname']);
            return $res;
        }
        return [];
    }

    public function getInfoByMobile($mobile)
    {
        $where = [
            'm.username' => $mobile,
        ];
        $field = 'wu.openid,m.id,m.nickname,m.sex, m.status, m.invite_code,wu.member_id';
        $res = $this->alias('wu')
            ->join('member m', 'wu.member_id=m.id', 'right')
            ->field($field)
            ->where($where)
            ->find();
        if (!empty($res)) {
            $res = $res->toArray();
            $res['nickname'] = $this->emojiDecode($res['nickname']);
            return $res;
        }
        return [];
    }


    /**
     * emoji解码
     * @param $str
     * @return mixed
     */
    private function emojiDecode($str)
    {
        $text = json_encode($str);
        $text = preg_replace_callback('/\\\\\\\\/i', function () {
            return '\\';
        }, $text);
        return json_decode($text);
    }

    /**
     * emoji编码
     * @param $str
     * @return mixed|string
     */
    public function emojiEncode($str)
    {
        if (!is_string($str)) return $str;
        if (!$str || $str == 'undefined') return '';
        $text = json_encode($str);
        $text = preg_replace_callback('/(\\\u[ed][0-9a-f]{3})/i', function ($str) {
            return addslashes($str[0]);
        }, $text);
        return json_decode($text);
    }
}